const router = require('koa-router')();
const cc = require('../conCtl');
const js = require('../jsCtl');
const db = require('../dbCtl');

/**
@hostpath = http://127.0.0.1/service/goods
 */

/** 获取活动列表列表
###
    GET {{hostpath}}?page=1&size=30
### */
router.get('/', async c => {
  let
    page = c.query.page || 1,
    size = c.query.size || 30,
    wName = c.query.key || '';

  let model = db.model('t_goods').where('state>0');
  if (wName)
    model = model.whereExtra('&& `name` like ?', `%${wName}%`);

  let data = await model.orderBy('dt desc').select(page, size);
  let count = await model.count();

  cc.send_list(c, data, count);
});

/** 创建商品/编辑商品
###
    PUT {{hostpath}}
### */
router.put('/', async c => {
  js.check_params(
    !c.request.body.name && '!名称' ||
    !c.request.body.intro && '!简介' ||
    !c.request.body.details && '!详情介绍' ||
    !c.request.body.cost_price && '!成本价' ||
    !c.request.body.starting_price && '!起拍价' ||
    !c.request.body.protective_price && '!保护价' ||
    !c.request.body.svaha_price && '!梭哈价' ||
    !c.request.body.bid_increment && '!加价幅度' ||
    !c.request.body.market_price && '!市场价');

  let data = c.request.body;
  if (!c.request.body.id) delete data.id;

  await db.model('t_goods').insertOrUpdate(data);

  cc.send(c);

});

/** 删除商品
###
    DEL {{hostpath}}
### */
router.del('/', async c => {
  js.check_params(!c.request.body.id && '!商品ID');

  let data = c.request.body;

  let state = await db.model('t_goods').where('id=?', data.id).shift('未找到指定对象', 'state');
  if (state == 2)
    js.throwObj('使用中的商品不可删除', js.rescode.fail);

  await db.model('t_goods').where('id=?', data.id).relyUpdate('删除失败',{
    state: 0
  });

  cc.send(c);
});





/** 获取未使用商品列表
###
    GET {{hostpath}}/select?page=1&size=30
### */
router.get('/select', async c => {
  let
    page = c.query.page || 1,
    size = c.query.size || 30;

  let model = db.model('t_goods').where('repertory_type=1||(state=1 && dt_freeze<NOW())');

  let data = await model.orderBy('dt desc').select(page, size);
  let count = await model.count();

  cc.send_list(c, data, count);
});


module.exports = router;